package com.smartcampusbackend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartcampusbackend.model.SystemLog;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.SystemLogService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/logs")
@Slf4j
public class SystemLogController {
    
    @Autowired
    private SystemLogService systemLogService;
    
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 分页查询日志
     */
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getLogsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String logType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request
    ) {
        try {
            // 检查权限
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }
            
            // 只有管理员可以查看所有日志，其他用户只能查看自己的日志
            if (!"ADMIN".equals(currentUser.getRole())) {
                username = currentUser.getUsername();
            }
            
            Page<SystemLog> pageParam = new Page<>(page, size);
            IPage<SystemLog> result = systemLogService.getLogsByPage(pageParam, username, logType, status, startDate, endDate);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询日志失败", e);
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", "查询日志失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取今日统计
     */
    @GetMapping("/stats/today")
    public ResponseEntity<Map<String, Object>> getTodayStats(HttpServletRequest request) {
        try {
            // 检查权限
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }
            
            // 只有管理员可以查看统计
            if (!"ADMIN".equals(currentUser.getRole())) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }
            
            Map<String, Object> stats = systemLogService.getTodayStats();
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取统计成功");
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取今日统计失败", e);
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", "获取统计失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取用户最近日志
     */
    @GetMapping("/recent")
    public ResponseEntity<Map<String, Object>> getRecentLogs(
            @RequestParam(defaultValue = "4") int limit,
            HttpServletRequest request
    ) {
        try {
            // 检查权限
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }
            
            List<SystemLog> logs = systemLogService.getRecentLogsByUsername(currentUser.getUsername(), limit);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取最近日志成功");
            response.put("data", logs);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取最近日志失败", e);
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", "获取最近日志失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取时间范围统计
     */
    @GetMapping("/stats/range")
    public ResponseEntity<Map<String, Object>> getLogStatsByRange(
            @RequestParam String startDate,
            @RequestParam String endDate,
            HttpServletRequest request
    ) {
        try {
            // 检查权限
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }
            
            // 只有管理员可以查看统计
            if (!"ADMIN".equals(currentUser.getRole())) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }
            
            List<Map<String, Object>> stats = systemLogService.getLogStatsByDateRange(startDate, endDate);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取统计成功");
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取时间范围统计失败", e);
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", "获取统计失败: " + e.getMessage()));
        }
    }
    
    /**
     * 导出日志
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportLogs(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String logType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request
    ) {
        try {
            // 检查权限
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).build();
            }
            
            // 只有管理员可以导出所有日志，其他用户只能导出自己的日志
            if (!"ADMIN".equals(currentUser.getRole())) {
                username = currentUser.getUsername();
            }
            
            byte[] excelData = systemLogService.exportLogs(username, logType, status, startDate, endDate);
            
            String filename = "系统日志_" + System.currentTimeMillis() + ".xlsx";
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", encodedFilename);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelData);
        } catch (Exception e) {
            log.error("导出日志失败", e);
            return ResponseEntity.status(500).build();
        }
    }
    
    /**
     * 导出PDF日志
     */
    @GetMapping("/export/pdf")
    public ResponseEntity<byte[]> exportLogsPDF(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String logType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request
    ) {
        try {
            // 检查权限
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                log.warn("导出PDF日志失败：用户未登录");
                return ResponseEntity.status(401).build();
            }
            
            log.info("导出PDF日志：用户 {} 角色 {}", currentUser.getUsername(), currentUser.getRole());
            
            // 只有管理员可以导出所有日志，其他用户只能导出自己的日志
            if (!"ADMIN".equals(currentUser.getRole())) {
                username = currentUser.getUsername();
                log.info("非管理员用户，限制只能导出自己的日志：{}", username);
            }
            
            byte[] pdfData = systemLogService.exportLogsPDF(username, logType, status, startDate, endDate);
            
            String filename = "系统日志_" + System.currentTimeMillis() + ".pdf";
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", encodedFilename);
            
            log.info("PDF导出成功，文件大小：{} bytes", pdfData.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfData);
        } catch (Exception e) {
            log.error("导出PDF日志失败", e);
            return ResponseEntity.status(500).build();
        }
    }
    
    /**
     * 获取当前登录用户信息
     */
    private User getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        log.info("Received Authorization header: {}", token);
        
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            log.info("Extracted token: {}", token);
            
            String username = tokenService.getUsernameByToken(token);
            log.info("Username from token: {}", username);
            
            if (username != null) {
                User user = userService.getByUsername(username);
                if (user != null) {
                    log.info("Current user: {} with role: {}", username, user.getRole());
                    return user;
                } else {
                    log.warn("User not found for username: {}", username);
                }
            } else {
                log.warn("Token not found in TokenService: {}", token);
            }
        } else {
            log.warn("Invalid Authorization header: {}", token);
        }
        return null;
    }
} 